package com.hnevc.contentproviderdemo;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.w3c.dom.Text;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";
    public static final int REQUEST_CODE = 101;
    Button mBtnShowNews,mBtnAddNews;
    ListView mLvNews;
    List<News> mNewsList;
    private MyNewsBaseAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initEvent();
    }

    private void initEvent() {
        mBtnShowNews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showNews();
            }
        });
        mBtnAddNews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addNews();
            }
        });
        registerForContextMenu(mLvNews);

    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info
                = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        switch (item.getItemId()){
            case R.id.id_menu_item_delete:
                //TODO 删除
                deleteNews(position);
                break;
            case R.id.id_menu_item_update:
                //TODO 修改
                Intent intent = new Intent(this,ModifyActivity.class);
                News news = mNewsList.get(position);
                intent.putExtra("_id",news.get_id());
                startActivityForResult(intent, REQUEST_CODE);
                break;
        }


        return super.onContextItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == ModifyActivity.RESULT_CODE){
            if(requestCode == REQUEST_CODE){
                int _id = data.getIntExtra("_id",0);
                if(_id>0){
                    News news = getNewsById(_id);
                    if(news!=null){
                        news.setTitle(data.getStringExtra("title"));
                        news.setAuthor(data.getStringExtra("author"));
                        news.setContent(data.getStringExtra("content"));
                        news.setPublishDate(data.getStringExtra("publishDate"));
                        mAdapter.notifyDataSetChanged();
                    }

                }


            }
        }
    }

    private News getNewsById(int id) {
        for (int i = 0; i < mNewsList.size(); i++) {
            if(mNewsList.get(i).get_id() == id){
                return mNewsList.get(i);
            }
        }
        return null;
    }

    private void deleteNews(int position) {
        Uri uri = Uri.parse("content://com.hnevc.contentproviderdemo/news");
        ContentResolver contentresolver = getContentResolver();
        int id = mNewsList.get(position).get_id();
        int num = contentresolver.delete(uri,"_id=?",new String[]{id +""});
        if(num>0){
            mNewsList.remove(position);
            mAdapter.notifyDataSetChanged();
        }else {

        }

    }

    private void addNews() {
        Uri uri = Uri.parse("content://com.hnevc.contentproviderdemo/news");
        ContentValues values = new ContentValues();
        values.put("title","中共十九大");
        values.put("author","TOM");
        values.put("content","中国共产党第十九次代表大会，于2017-10-18日在北京人民大会堂召开！");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String publishDate = sdf.format(Calendar.getInstance().getTime());
        values.put("publishDate",publishDate);

        ContentResolver resolver = getContentResolver();
        Uri newRowUri = resolver.insert(uri,values);
        Toast.makeText(this, "添加成功"+newRowUri.toString(), Toast.LENGTH_SHORT).show();
        Log.e(TAG, "addNews: "+ "添加成功"+newRowUri.toString());
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        this.getMenuInflater().inflate(R.menu.edit_menu,menu);
    }


    private void showNews() {
        mNewsList = new ArrayList<News>();
        Uri uri = Uri.parse("content://com.hnevc.contentproviderdemo/news");
        ContentResolver contentReslover = getContentResolver();
        Cursor cursor = contentReslover.query(uri,
                new String[]{"_id","title","author","content","publishDate"},
                null,null,null);
        while (cursor.moveToNext()){
            News news = new News();
            news.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
            news.setTitle(cursor.getString(cursor.getColumnIndex("title")));
            news.setAuthor(cursor.getString(cursor.getColumnIndex("author")));
            news.setContent(cursor.getString(cursor.getColumnIndex("content")));
            news.setPublishDate(cursor.getString(cursor.getColumnIndex("publishDate")));
            mNewsList.add(news);
        }
        cursor.close();
        mAdapter = new MyNewsBaseAdapter();

        mLvNews.setAdapter(mAdapter);
    }

    private void initView() {

        mBtnShowNews = (Button) findViewById(R.id.id_btn_query_news);
        mBtnAddNews = (Button) findViewById(R.id.id_btn_add_news);
        mLvNews = (ListView) findViewById(R.id.id_lv_news);



    }

    public class MyNewsBaseAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mNewsList.size();
        }

        @Override
        public Object getItem(int i) {
            return mNewsList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return mNewsList.get(i).get_id();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item,null);
            TextView tvTitle = (TextView) view.findViewById(R.id.id_tv_title);
            TextView tvPublishDate = (TextView) view.findViewById(R.id.id_tv_publis_date);
            tvTitle.setText(mNewsList.get(i).getTitle());
            tvPublishDate.setText(mNewsList.get(i).getPublishDate().substring(0,10));
            return view;
        }
    }
}
